package com.zixuan.sina.config.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zixuan.sina.config.redis.RedisService;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.utils.JwtUtils;
import com.zixuan.sina.utils.LoginResult;
import com.zixuan.sina.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 登录成功处理接口
 */
@Data
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;
    @Value("${request.login.tokenKey}")
    private String tokenKey;
    @Resource
    RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        User user = (User) authentication.getPrincipal();//获取登录信息转换成json写到浏览器
        //生成JWT
        String token = jwtUtils.generateToken(user);
        long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();//获取过期时间
        LoginResult loginResult = new LoginResult(user.getId(), ResultCode.SUCCESS,token,expireTime);
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        OutputStream outputStream=response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
        //将token存入redis
        redisService.set(tokenKey+token,token,jwtUtils.getExpiration()/1000);

    }
}
